#include "unp.h"

int
main() {
    int                 listenfd, connfd;
    pid_t               childpid;
    socklen_t           clilen;
    struct sockaddr_in  cliaddr, servaddr;
    char                cliip[INET_ADDRSTRLEN];

    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("openning sock stream");
        exit(1);
    }

    bzero(&servaddr, sizeof(struct sockaddr_in));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(SERV_PORT);

    if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("binding stream socket");
        exit(1);
    }

    if (listen(listenfd, LISTENQ) == -1) {
        perror("listening stream socket");
        exit(1);
    }

    for ( ; ; ) {
        clilen = sizeof(cliaddr);
        if ((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen)) < 0) {
            perror("accept the client socket");
            continue;
        }
        //打印客户IP
        if (inet_ntop(AF_INET, &cliaddr.sin_addr, cliip, INET_ADDRSTRLEN) == NULL) {
            perror("inet_ntop.");
            exit(EXIT_FAILURE);
        }
        printf("accept 来自%s 的连接...\n", cliip);
        if ((childpid = fork()) == 0) {
            close(listenfd);
            str_echo(connfd);
            exit(0);
        }
        close(connfd);
    }

    return 0;
}
